<?php

namespace App\Http\Controllers\Admin\Goods;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Goods\Speci as SpeciModel ;
use App\Models\Goods\SpeciValue as SpeciValueModel ;
use Illuminate\Support\Facades\DB;



class SpeciController extends Controller
{

    public function lists(){
        $result = SpeciModel::all();
        $data = [
            "code"=> 0,
            "msg"=> "",
            "count"=> count($result),
            "data"=>$result
        ];
        return json_encode($data);
    }

    public function getSpeciValues(Request $request){
        $params = $request->all();
        if(is_array($params['id'])){
            foreach ($params['id'] as $k=>$v){
                $res[$k]['speci'] = SpeciModel::find(intval($v));
                $res[$k]['speci_value'] = SpeciValueModel::where('speci_id',intval($v))->get();
            }
        }
        return showMsg(200,'ok', $res);

    }

    public function add(Request $request){

        $params = $request->all();

        //实务操作
        DB::beginTransaction();

        $speci = new SpeciModel;
        $speci->name = $params['experimentTypeName'];
        $speci->save();

        $speci_id = $speci->id; //获取插入之后返回的id
        if($speci_id){
            $event = new SpeciValueModel();

            $arr_speci_tmp = json_decode($params['expListJson'],true);
            $arr_speci = [];
            foreach ($arr_speci_tmp as $k => $v){
                $arr_speci[$k]['name'] = $v['experimentName'];
                $arr_speci[$k]['speci_id'] = intval($speci_id);
            }
//此处在课程中做一个优化方案
            if ($event->addAll($arr_speci)){
                DB::commit();
                return showMsg(200, '添加成功');
            } else{

                DB::rollBack();
            }
        }else{
            return showMsg(0, '添加失败');
        }


    }




}
